using Kickball.Step1;
using Kickball.Step2;
using Kickball.Step3;
using Unity.Burst;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;

namespace Kickball.Step5
{
    public partial struct BallKickingSystem : ISystem
    {
        [BurstCompile]
        public void OnCreate(ref SystemState state)
        {
            state.RequireForUpdate<Execute.BallKicking>();
            state.RequireForUpdate<Config>();
        }

        [BurstCompile]
        public void OnUpdate(ref SystemState state)
        {
            if (!Input.GetKeyDown(KeyCode.Space)) return;

            var config = SystemAPI.GetSingleton<Config>();

            //踢指定范围内的所有球
            foreach (var playerTrans in SystemAPI.Query<RefRO<LocalTransform>>()
                         .WithAll<Player>()
                         .WithDisabled<Carry>())
            {
                foreach (var (ballTrans, velocity) in SystemAPI.Query<RefRO<LocalTransform>, RefRW<Velocity>>()
                             .WithAll<Ball>())
                {
                    float distSq = math.distancesq(playerTrans.ValueRO.Position, ballTrans.ValueRO.Position);

                    if (distSq < config.BallKickingRangeSq)
                    {
                        //踢球
                        var playerToBall =
                            math.normalizesafe(ballTrans.ValueRO.Position.xz - playerTrans.ValueRO.Position.xz);
                        velocity.ValueRW.Value += playerToBall * config.BallKickForce;
                    }
                }
            }
        }
    }
}